<?
/*--|	FRIEND
  Software: Socially
   Version: 1.0
   Contact: http://socially.googlecode.com
      Info: http://socially.googlecode.com
   Support: http://socially.googlecode.com
--------------------------------------------------------------------------
    Author: goker.cebeci | http://gokercebeci.com
--------------------------------------------------------------------------
   License: Distributed under the GNU General Public License (GPL)
            http://www.gnu.org/licenses/gpl.html
 This program is distributed in the hope that it will be useful - WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE.
-------------------------------------------------------------------------*/
// status request,friend,block
class friend {
    /**
     * $memberOne < $memberTwo ? one : two
     *
     * @param int $memberOne
     * @param int $memberTwo
     * @return array
     */
    private static function _order($memberOne, $memberTwo){
        return ($memberOne < $memberTwo)?array($memberOne,$memberTwo,'one'):array($memberTwo,$memberOne,'two');
    }
    private static function _add($memberOne, $memberTwo, $status = 'request'){
        if($memberOne == $memberTwo) return true;
        list($memberOne, $memberTwo, $sender) = self::_order($memberOne, $memberTwo);
        db::query(sprintf("INSERT INTO friends (memberOne,memberTwo,sender,status,date)
            VALUES ('%d','%d','%s','%s',NOW())
            ON DUPLICATE KEY UPDATE sender = '%s', status = '%s', `date` = NOW();"
            ,$memberOne,$memberTwo,$sender,$status,$sender,$status));
        return true;
    }
    private static function _get($a){
        if($a['list']){
        $r = db::query(sprintf("SELECT IF(memberOne='%s',memberTwo,memberOne) as ID FROM friends WHERE 1=1",$a['UID'])
            .($a['ID']?sprintf(" AND ID = %d",$a['ID']):'')
            .($a['sender']?sprintf(" AND ((memberOne = %d AND sender = 'one') OR (memberTwo = %d AND sender = 'two'))",$a['UID'],$a['UID']):'')
            .($a['recipient']?sprintf(" AND ((memberOne = %d AND sender = 'two') OR (memberTwo = %d AND sender = 'one'))",$a['UID'],$a['UID']):'')
            .($a['match']?sprintf(" AND (memberOne = %d OR memberTwo = %d)",$a['UID'],$a['UID']):'')
            .($a['status']?sprintf(" AND status = '%s'",$a['status']):'')
            .($a['limit']?sprintf(" LIMIT %d",$a['limit']):'')
            .';',true,true);
            if($r) foreach ($r as $k=>$i){
                $r[$k] = profile::get(array('ID'=>$i->ID));
            }
        } elseif($a['online']){
            $r =  db::query(sprintf("SELECT IF(memberOne='%s',memberTwo,memberOne) as ID FROM friends
                    WHERE (memberOne = %d OR memberTwo = %d)
                    AND memberOne IN (SELECT ID FROM accountOnline WHERE status <> 'offline')
                    AND memberTwo IN (SELECT ID FROM accountOnline WHERE status <> 'offline') ",$a['UID'],$a['UID'],$a['UID'])
            .($a['status']?sprintf(" AND status = '%s'",$a['status']):'')
            .' ORDER BY ID '
            .($a['limit']?sprintf(" LIMIT %d",$a['limit']):'')
            .';',true,true);
            if($r) foreach ($r as $k=>$i){
                $r[$k] = profile::get(array('ID'=>$i->ID));
            }
        } elseif($a['count']){
            $r = db::query('SELECT COUNT(memberOne) as total FROM friends WHERE 1=1'
                .($a['sender']?sprintf(" AND ((memberOne = %d AND sender = 'one') OR (memberTwo = %d AND sender = 'two'))",$a['UID'],$a['UID']):'')
                .($a['recipient']?sprintf(" AND ((memberOne = %d AND sender = 'two') OR (memberTwo = %d AND sender = 'one'))",$a['UID'],$a['UID']):'')
                .($a['match']?sprintf(" AND (memberOne = %d OR memberTwo = %d)",$a['UID'],$a['UID']):'')
                .($a['status']?sprintf(" AND status = '%s'",$a['status']):'')
                .';',true);
            $r = $r->total;
        }
        return $r;
    }
/* -----------------------------------------------------------------------
	PUBLIC FUNCTIONS
 ------------------------------------------------------------------------*/
	
/* -----------------------------------------------------------------------
	SPECIAL FUNCTIONS
 ------------------------------------------------------------------------*/
    /**
     * friend request function [update status = request]
     *
     * @param big_int $memberOne
     * @param big_int $memberTwo
     * @return object
     */
    public static function request($memberOne, $memberTwo){
        self::_add($memberOne, $memberTwo);
        // notification mail
        $sender = account::get(array('ID'=>$memberOne));
        $message = sprintf(_('You have a new friend request from %s.<br /> %sclick here to show requests%s.'),
                    '<a href="http://'.DOMAIN.'/'.$sender->url.'">'.$sender->name.'</a>',
                    '<a href="http://'.DOMAIN.'/'.LANG.'/friend/requests">','</a>');
        notification::mail(array('application'=>'friend','sender'=>$memberOne,'recipient'=>$memberTwo,'message'=>$message));
        // result
        return common::result(200,_('Your request has been sent.'));
    }
    /**
     * friend request approve [update status = friend]
     *
     * @param big_int $memberOne
     * @param big_int $memberTwo
     * @return object
     */
    public static function approve($memberOne, $memberTwo){
        if($memberOne == $memberTwo) return common::result(600,_('Please try again later..'));
        //notification
        notification::send(array('application'=>'friend','notification'=>'approve','sender'=>$memberOne,'recipient'=>$memberTwo));
        //
        $accounID = $memberOne;
        list($memberOne, $memberTwo, $sender) = self::_order($memberOne, $memberTwo);
        $sender = $memberOne == $accounID?'two':'one';
        db::query(sprintf("UPDATE friends SET status = 'friend', `date` = NOW()
                WHERE memberOne = '%d' AND memberTwo = '%d' AND sender = '%s' AND status = 'request' LIMIT 1;",
                $memberOne,$memberTwo,$sender));
        // result
        return common::result(200);
    }
    /**
     * friend request decline [call self::remove]
     *
     * @param big_int $memberOne
     * @param big_int $memberTwo
     * @return object
     */
    public static function reject($memberOne, $memberTwo){
        return self::remove($memberOne, $memberTwo);
    }
	/**
	 * friend request decline [delete record]
	 *
	 * @param big_int $memberOne
	 * @param big_int $memberTwo
	 * @return object
	 */	
	public static function remove($memberOne, $memberTwo){
            if($memberOne == $memberTwo) return common::result(600,_('Please try again later..'));
            list($memberOne, $memberTwo, $sender) = self::_order($memberOne, $memberTwo);
            db::query(sprintf("DELETE FROM friends
                WHERE memberOne = '%d' AND memberTwo = '%d' AND status <> 'block' LIMIT 1;",
                $memberOne,$memberTwo));
            return common::result(200);
	}
	/**
	 * block member [status = block]
	 *
	 * @param big_int $memberOne
	 * @param big_int $memberTwo
	 * @return object
	 */	
	public static function block($memberOne, $memberTwo){
            if($memberOne == $memberTwo) return common::result(600,_('Please try again later..'));
            self::_add($memberOne, $memberTwo, 'block');
            return common::result(200);
	}
	/**
	 * unblock member [delete record if sender]
	 *
	 * @param big_int $memberOne
	 * @param big_int $memberTwo
	 * @return object
	 */	
	public static function unblock($memberOne, $memberTwo){
		if($memberOne == $memberTwo) return common::result(600,_('Please try again later..'));
		list($memberOne, $memberTwo, $sender) = self::_order($memberOne, $memberTwo);
		db::query(sprintf("DELETE FROM friends 
			WHERE memberOne = '%d' AND memberTwo = '%d' AND sender = '%s' LIMIT 1;",
			$memberOne,$memberTwo,$sender));
		return common::result(200);
	}
	/**
	 * request list 
	 *
	 * @param array $a
	 * @return object
	 */
	public static function requests(array $a){
		$a['recipient'] = true;
		$a['status'] = 'request';
		return self::_get($a);
	}
	/**
	 * friend list 
	 *
	 * @param array $a
	 * @return object
	 */
	public static function friends(array $a){
		$a['match'] = true;
		$a['status'] = 'friend';
		return self::_get($a);
	}
	/**
	 * block list 
	 *
	 * @param array $a
	 * @return object
	 */
	public static function blocks(array $a){
		$a['sender'] = true;
		$a['status'] = 'block';
		return self::_get($a);
	}
	/**
	 * check friend and friend request
	 *
	 * @param big_int $memberOne
	 * @param big_int $memberTwo
	 * @return object
	 */
	public static function check($memberOne,$memberTwo){
		if($memberOne == $memberTwo) return true;
		list($memberOne, $memberTwo, $sender) = self::_order($memberOne, $memberTwo);
		$r = db::query(sprintf("SELECT sender,status FROM friends 
			WHERE memberOne = %d AND memberTwo = %d LIMIT 1;",
			$memberOne,$memberTwo),true);
		return $r->sender==$sender?$r->status:($r->status=='request'?'':$r->status);
	}
/*	
	public static function invite($a){		
		if(!ereg("^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$",$a['email'])) return common::result(1, true);
		if($ID = account::add($a)){
			self::add($a['memberOne'],$ID,1);			
			return common::result(200, array(405,$a['memberOne'],$ID,0));
		} else return common::result(800);
	}
*/

    
    public static function notification($ID, $sender, $item = null){
        $notification = array(
            'approve' => sprintf(dgettext('friend','%s accepted your friend request. %sclick here to show friends%s.')
                    ,'<a href="http://'.DOMAIN.$sender->url.'">'.$sender->fullname.'</a>'
                    ,'<a href="http://'.DOMAIN.'/'.LANG.'/friend">','</a>')
            );
        return $notification[$ID];
    }
}
?>